#!/usr/bin/python
# -*- coding: UTF-8 -*-    
# Author:Jruing
# FileName:wxpusherAPI
# DateTime:2021/7/21 13:24
# SoftWare: PyCharm

import requests


class WxPusher():
    """
        Document :https://wxpusher.zjiecode.com/docs/#/
         _          __ __    __  _____   _   _   _____   _   _   _____   _____
        | |        / / \ \  / / |  _  \ | | | | /  ___/ | | | | | ____| |  _  \
        | |  __   / /   \ \/ /  | |_| | | | | | | |___  | |_| | | |__   | |_| |
        | | /  | / /     }  {   |  ___/ | | | | \___  \ |  _  | |  __|  |  _  /
        | |/   |/ /     / /\ \  | |     | |_| |  ___| | | | | | | |___  | | \ \
        |___/|___/     /_/  \_\ |_|     \_____/ /_____/ |_| |_| |_____| |_|  \_\
        """
    def __init__(self, app_token: str):
        self._app_token = app_token
        self._api_urls = {"send_msg": "http://wxpusher.zjiecode.com/api/send/message",
                          "status_check": "http://wxpusher.zjiecode.com/api/send/query/{0}",
                          "create_qrcode": "http://wxpusher.zjiecode.com/api/fun/create/qrcode",
                          "user_follow": "http://wxpusher.zjiecode.com/api/fun/wxuser/v2",
                          "block_user": "http://wxpusher.zjiecode.com/api/fun/reject",
                          "del_user": "http://wxpusher.zjiecode.com/api/fun/remove"}
        self._header = {"Content-Type": "application/json"}

    def send_msg(self, content: str, topicIds: list, uids: list, url: str, summary: str = None,
                 contentType: int = 1) -> dict:
        """

        :param content: 消息内容
        :param summary: 消息摘要,限制长度100,当summary不传时,默认截取content前面的内容
        :param topicIds: 发送目标的topicId,如: [123]
        :param uids: 发送目标的UID 如["uid_123"],注意uids和topicIds可以同时填写,也可以只填写一个
        :param url:原文链接
        :param contentType:内容类型  1.文本 2.html(只需要发送body标签内的数据即可,不包含body标签)
        :return:

        example:
        {
            "appToken": "AT_xxx",
            "content": "Wxpusher祝你中秋节快乐!",
            "summary": "消息摘要",
            "contentType":1,
            "topicIds": [
                123
            ],
            "uids": [
                "UID_xxxx"
            ],
            "url": "http://wxpusher.zjiecode.com"
        }
        """
        topicIds = topicIds if isinstance(topicIds, list) and topicIds else []
        uids = uids if isinstance(uids, list) and uids else []
        params = {
            "appToken": self._app_token,
            "content": content,
            "summary": summary,
            "contentType": contentType,
            "topicIds": topicIds,
            "uids": uids,
            "url": url
        }

        response = requests.post(self._api_urls['send_msg'], json=params, headers=self._header)
        return response.json()

    def status_check(self, messageId):
        """

        :param messageId: 消息id
        :return:
        """
        response = requests.get(self._api_urls['status_check'].format(messageId))
        return response.json()

    def create_qrcode(self, extra: str, validTime: int = 1800) -> dict:
        """

        :param extra: 二维码携带的参数,最长64位
        :param validTime: 二维码有效期,默认30分钟,最长30天,单位为秒级
        :return:

        """
        params = {
            "appToken": self._app_token,
            "extra": extra,
            "validTime": validTime
        }
        response = requests.post(self._api_urls['create_qrcode'], json=params, headers=self._header)
        return response.json()

    def user_follow(self, page: int, pageSize: int, user_type: int = None, uid: str = None, isBlock: bool = None):
        """

        :param page: 页码
        :param pageSize:  分页大小，不能超过100
        :param user_type: 关注的类型，可选，不传查询所有用户，0是应用，1是主题。 返回数据
        :param uid: 用户的uid，可选，如果不传就是查询所有用户，传uid就是查某个用户的信息
        :param isBlock: 查询拉黑用户，可选，不传查询所有用户，true查询拉黑用户，false查询没有拉黑的用户
        :return:
        """
        params = {
            "appToken": self._app_token,
            "page": page,
            "pageSize": pageSize,
        }
        if pageSize > 100:
            raise Exception("pageSize 不能超过100")
        if uid:
            params['uid'] = uid

        if isBlock != None:
            params['isBlock'] = isBlock

        if user_type != None:
            params['type'] = user_type
        response = requests.get(self._api_urls['user_follow'], params=params)
        return response.json()

    def del_user(self, uid: str):
        """

        :param uid: 要删除的用户id,通过用户查询接口获取
        :return:
        """
        params = {
            "appToken": self._app_token,
            "id": uid
        }
        response = requests.delete(self._api_urls['del_user'], data=params)
        response.encoding = 'utf-8'
        return response.json()

    def block_user(self, uid: str, reject: bool = True):
        """

        :param uid: 用户id
        :param reject: 是否拉黑用户
        :return:
        """
        params = {
            "appToken": self._app_token,
            "id": uid,
            "reject": reject
        }
        response = requests.put(self._api_urls['block_user'], json=params)
        response.encoding = 'utf8'
        return response.json()


if __name__ == '__main__':
    uid = "UID_***********"
    wxpuser = WxPusher("AT_***********")
    # wxpuser.send_msg("diyi", [9394], ["UID_jeGcoGcRWeZ6i1QLEYAQl0KHwDA7"], "https://www.baidu.com",summary='')
    # wxpuser.status_check("212207007")
    # wxpuser.create_qrcode("uid")
    # wxpuser.user_follow(1, 10)
    # wxpuser.block_user(uid)
    # wxpuser.del_user(uid)
